package com.wangjiacai.utils.sms;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.wangjiacai.utils.enums.ResultEnum;
import com.wangjiacai.utils.web.exception.CodeMessageException;
import com.wangjiacai.utils.web.properties.SmsProperty;
import org.springframework.beans.factory.annotation.Autowired;

public class DefaultSmsCodeSender implements SmsCodeSender {

    @Autowired
    private SmsProperty smsProperty;

    @Autowired
    private SmsSingleSender sender;

    @Override
    public void send(String mobile, String code) {
        SmsSingleSenderResult result = null;
        send("86", mobile, code,1);
    }

    @Override
    public void send(String area, String mobile, String code) {
        send(area,mobile,code,1,smsProperty.getTemplateId());
    }

    @Override
    public void send(String area, String mobile, String code, String template) {
        send(area,mobile,code,1,template);
    }

    @Override
    public void send(String area, String mobile, String code, int minute) {
        send(area,mobile,code,minute,smsProperty.getTemplateId());
    }

    @Override
    public void send(String area, String mobile, String code, int minute, String template) {
        SmsSingleSenderResult result = null;
        try {
            String[] params = {code, minute+""};
            int templateId = smsProperty.getTemplateMap().get(template);
            String sign = smsProperty.getSign();
            result = sender.sendWithParam(area, mobile, templateId, params, sign, "", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(result==null) throw new CodeMessageException(ResultEnum.CodeServiceInvalid);
        if ( result.result!=0) throw new CodeMessageException(result.errMsg);
    }

    private void send(String area, String mobile, String code, int minute, Integer templateId) {
        SmsSingleSenderResult result = null;
        try {
            String[] params = {code, minute+""};
            String sign = smsProperty.getSign();
            result = sender.sendWithParam(area, mobile, templateId, params, sign, "", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result == null || result.result!=0) {
            throw new CodeMessageException(ResultEnum.CodeServiceInvalid);
        }
    }

}
